import React, { useState, useEffect } from 'react';
import styles from '../css/mine.module.css';
import tree from '../assets/tree.png';
import meImg from '../assets/tree.png';
import blockImg from '../assets/top.png';
import starttwoImg from '../assets/starts.png';
import startoneImg from '../assets/starts.png';
import starthreeImg from '../assets/starts.png';
import send from '../assets/send.png';
import mines from '../assets/mine1.png';
import { useNavigate } from 'react-router-dom';
import hourse2 from '../assets/hourse.png';
import flower from '../assets/flower.png';
import please from '../assets/please.png';
import please1 from '../assets/please1.png';
import eye from '../assets/eye.png';
import gift from '../assets/gift.png';
import order from '../assets/gift.png';
import messages from '../assets/gift.png';
import code from '../assets/code.png';
import money from '../assets/money.png';
import collect from '../assets/collect.png';
import good from '../assets/goods.png';
import line from '../assets/line.png';
import trues from '../assets/true.png';
import all from '../assets/all.png';
import wait from '../assets/wait.png';
import cancel from '../assets/cancel.png';
import pay from '../assets/speech.png';
import right from '../assets/right1.png';
import head from '../assets/heads.jpg';
import errorAvater from '../assets/pandaback.png';
import { message } from 'antd';
import { Toast } from 'antd-mobile';
import { fetchMyStrategies } from '../api/mineApi';
import { imgUrl } from '../config'; // 导入imgUrl
const Mine = () => {
  const [datas, setDatas] = useState([]);
  const [mine, setMine] = useState({});
  const navigate = useNavigate();
  const [array, setArray] = useState([
    { img: all, name: "全部", status: 1 },
    { img: wait, name: "待支付", status: 2 },
    { img: cancel, name: "已取消", status: 3 },
    { img: pay, name: "已支付", status: 4 }
  ]);

  // 初始化加载数据
 // 初始化加载数据
useEffect(() => {
  // 加载我的攻略数据
const fetchData = async () => {
  try {
    const response = await fetchMyStrategies();
    if (response && response.code === 1 && Array.isArray(response.data)) {
      setDatas(response.data);
    } else {
      console.error('接口返回数据格式不正确:', response);
      message.error('获取攻略数据失败，请稍后重试');
    }
  } catch (error) {
    console.error('获取我的攻略数据时出错:', error);
    message.error('获取攻略数据失败，请检查网络或稍后重试');
  }
};

  fetchData();

  // 加载用户数据
  const mineData = JSON.parse(sessionStorage.getItem("mine"));
  if (mineData) {
    setMine(mineData);
    console.log(mineData);
  } else {
    console.error('未找到用户数据');
  }

  // 设置用户性别相关样式
  if (mineData && mineData.sex === 1) {
    console.log("男");
    // 这里需要通过 ref 或直接操作 DOM 来设置样式，或者使用状态管理样式
  } else if (mineData) {
    console.log("女");
    // 这里需要通过 ref 或直接操作 DOM 来设置样式，或者使用状态管理样式
  }
}, []);

  
    // 跳转发布页面
    const aircraft = () => {
        const aircraftElement = document.querySelector(`.${styles.aircraft} img`);
        if (aircraftElement) {
            aircraftElement.style.marginTop = "-2000px";
            aircraftElement.style.transition = "all 2s";
            setTimeout(() => {
                navigate("/issue");
            }, 2000);
        }
    };

    // 跳转攻略详情
    const no = (i, id) => {
        const selectedStrategy = datas[i];
        if (selectedStrategy) {
            sessionStorage.setItem("game", JSON.stringify(selectedStrategy));
            sessionStorage.setItem("gameimg", selectedStrategy.img || "");
            navigate("/strategy");
        } else {
            console.error("未找到对应的攻略数据");
            message.error("攻略数据加载中，请稍后再试");
        }
    };

    // 跳转我的订单页面
    const handleOrderClick = () => {
        navigate("/orderPage");
    };

    // 浏览记录
    const handleBrowseClick = () => {
        Toast.show({
            content: '此功能开发中...',
        });
    };

    // 收藏记录
    const handleCollectClick = () => {
        sessionStorage.setItem("stat", 1);
        navigate("/browse");
    };

    // 点赞记录
    const handleLikeClick = () => {
        sessionStorage.setItem("stat", 2);
        navigate("/browse");
    };

    // 跳转奖品页面
    const award = () => {
        window.location.href = "awardItem.html";
    };

    // 订单图标的点击事件
    const icon_item = (i, status) => {
        sessionStorage.setItem("statusMine", status);
        sessionStorage.setItem("statusIndex", i);
        navigate("/orderPage");
    };

    const photoAlbum = () => {
        // window.location.href = "photoAlbum.html";
    };

    // 图片加载出错处理函数
    const handleImageError = (e) => {
        e.target.src = errorAvater;
    };

    // 提示开发中的点击处理函数
    const prize = () => {
        navigate("/prize");
    };

    const handleFeatureUnderDevelopment = () => {
        Toast.show({
            content: '此功能开发中...',
        });
    };

    return (
        <div style={{ backgroundColor: '#e9ecf4' }}>
            {/* mine */}
              <div className={styles.top}>
        <b id={styles.mine}>我的</b>
        <div className={styles.image}>
          <img onClick={prize} id={styles.head} src={mine.img ? head : head} alt="" onError={handleImageError} />
          <div>
            <b id={styles.name}>{mine.nickname || 'lv'}</b>
            <span>推荐人：无</span>
          </div>
        </div>
        <div className={styles.travel}>
          <p>旅游达人</p>
          <span>畅行一路通，出游最轻松</span>
        </div>
      </div>

            <div className={styles.fif}>
                <div className={styles.fifBlock} onClick={handleFeatureUnderDevelopment}>
                    <img className={styles.ones} src={mine.sex === 1 ? eye : eye} alt="" onError={handleImageError} />
                    <span>浏览记录</span>
                </div>
                <div className={styles.fifBlock} >
                    <img className={styles.twos} src={mine.sex === 1 ? gift : gift} alt="" onError={handleImageError} />
                    <span>我的奖品</span>
                </div>
                <div className={styles.fifBlock} onClick={handleOrderClick}>
                    <img className={styles.threes} src={mine.sex === 1 ? order : order} alt="" onError={handleImageError} />
                    <span>我的订单</span>
                </div>
                <div className={styles.fifBlock} onClick={handleFeatureUnderDevelopment}>
                    <img className={styles.fours} src={mine.sex === 1 ? messages : messages} alt="" onError={handleImageError} />
                    <span>推广信息</span>
                </div>
                <div className={styles.fifBlock} onClick={handleFeatureUnderDevelopment}>
                    <img className={styles.fifs} src={mine.sex === 1 ? code : code} alt="" onError={handleImageError} />
                    <span>推广码</span>
                </div>
            </div>

            <div className={styles.else}>
                <div className={styles.elseOne}>
                    <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                        <b>我的团队</b>
                        <b>0</b>
                    </div>
                    <img className={styles.sex} src={mine.sex === 1 ? please1 : please1} alt="" onError={handleImageError} />
                </div>
                <div className={styles.elseTwo}>
                    <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                        <b>收益</b>
                        <b>0</b>
                    </div>
                    <img src={money} alt="" onError={handleImageError} />
                </div>
            </div>

            <div className={styles.eight}>
                <b>其他服务</b>
                <div className={styles.eightOne}>
                    <div className={styles.eightBlock} id={styles.cloect} onClick={handleCollectClick}>
                        <img src={collect} alt="" onError={handleImageError} />
                        <span>收藏记录</span>
                    </div>
                    <div className={styles.eightBlock} id={styles.good} onClick={handleLikeClick}>
                        <img src={good} alt="" onError={handleImageError} />
                        <span>点赞记录</span>
                    </div>
                    <div className={styles.eightBlock} onClick={handleFeatureUnderDevelopment}>
                        <img src={line} alt="" onError={handleImageError} />
                        <span>在线记录</span>
                    </div>
                    <div className={styles.eightBlock} onClick={handleFeatureUnderDevelopment}>
                        <img src={trues} alt="" onError={handleImageError} />
                        <span>实名认证</span>
                    </div>
                </div>
                <div className={styles.eightOnes}>
                    {array.map((item, i) => (
                        <div key={i} className={styles.eightBlock} onClick={() => icon_item(i, item.status)}>
                            <img src={item.img} alt="" onError={handleImageError} />
                            <span>{item.name}</span>
                        </div>
                    ))}
                </div>
            </div>

            {/* 攻略 */}
            <div className={styles.look}>
                <b>我的攻略</b>
                <div style={{ display: 'flex', alignItems: 'center' }} onClick={() => navigate("/game")}>
                    <span>查看全部</span>
                    <img src={right} alt="" onError={handleImageError} />
                </div>
            </div>
            <div className={`${styles.item} ${styles.maxStrategy}`} style={{ paddingBottom: '50px' }}>
                {datas.slice(0, 5).map((item, i) => (
                    <div key={i} className={styles.strategys} onClick={() => no(i, item.id)}>
                        <img src={`${imgUrl}${item.img}`} alt="" onError={handleImageError} />
                        <p>{item.title}</p>
                        <div className={styles.strategyContent}>
                            <div className={styles.strategyOne}>
                                <img style={{ width: '27px', height: '27px', borderRadius: '27px', objectFit: 'cover', marginLeft: '5px' }} src={`${imgUrl}${item.avatar}`} alt="" onError={handleImageError} />
                                <span>{item.name}</span>
                            </div>

                        </div>
                    </div>
                ))}
            </div>

            {/* 底部导航栏 */}
            <div className={styles.bottom}>
                <div className={styles.second} onClick={() => navigate("/home")}>
                    <img src={hourse2} alt="" onError={handleImageError} />
                    <p style={{ color: 'black' }}>首页</p>
                </div>
                <div className={styles.first} onClick={() => navigate("/game")}>
                    <img src={flower} alt="" onError={handleImageError} />
                    <p>攻略</p>
                </div>
                <div className={styles.plane} onClick={aircraft}>
                    <div className={styles.aircraft}>
                        <img src={send} alt="" onError={handleImageError} />
                    </div>
                    <p style={{ marginTop: '33px', textAlign: 'center' }}>发布</p>
                </div>
                <div className={styles.first} onClick={() => navigate("/ranking")}>
                    <img src={tree} alt="" onError={handleImageError} />
                    <p>排行榜</p>
                </div>
                <div className={styles.first} onClick={() => navigate("/mine")}>
                    <img src={mines} alt="" onError={handleImageError} />
                    <p style={{ color: '#FF5050' }}>我的</p>
                </div>
            </div>
        </div>
    );
};

export default Mine;